package com.android.settings.audio.peq.peq.filter;

import static java.lang.Math.cos;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;

import com.android.settings.audio.peq.peq.Coeff;

/**
 * Created by We on 2023/3/18
 */
public class FilterHighShelf implements IFilter {
    /*
    function [coeff_b,coeff_a] = GetHighShelfEQ(f,Q,dBgain,fs)
        %%% highshelf EQ coeff
        w0      = 2*pi*f/fs;
        alpha   = sin(w0)/(2*Q);
        A       =   10^(dBgain/40);

        %%%highShelf: H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)
        b0 =    A*( (A+1) + (A-1)*cos(w0) + 2*sqrt(A)*alpha );
        b1 = -2*A*( (A-1) + (A+1)*cos(w0)                   );
        b2 =    A*( (A+1) + (A-1)*cos(w0) - 2*sqrt(A)*alpha );
        a0 =        (A+1) - (A-1)*cos(w0) + 2*sqrt(A)*alpha;
        a1 =    2*( (A-1) - (A+1)*cos(w0)                   );
        a2 =        (A+1) - (A-1)*cos(w0) - 2*sqrt(A)*alpha;

        %%%
        coeff_b=[b0,b1,b2]';
        coeff_a=[a0,a1,a2]';
    end
    * */

    @Override
    public Coeff getValue(double f, double Q, double dBGain, int fs) {
        //highshelf EQ coeff
        double w0 = 2 * Math.PI * f / fs;
        double alpha = sin(w0) / (2 * Q);
        double A = pow(10, dBGain / 40);

        //highShelf: H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)
        double b0 = A * ((A + 1) + (A - 1) * cos(w0) + 2 * sqrt(A) * alpha);
        double b1 = -2 * A * ((A - 1) + (A + 1) * cos(w0));
        double b2 = A * ((A + 1) + (A - 1) * cos(w0) - 2 * sqrt(A) * alpha);
        double a0 = (A + 1) - (A - 1) * cos(w0) + 2 * sqrt(A) * alpha;
        double a1 = 2 * ((A - 1) - (A + 1) * cos(w0));
        double a2 = (A + 1) - (A - 1) * cos(w0) - 2 * sqrt(A) * alpha;
        Coeff coeff = new Coeff();
        coeff.setB0(b0);
        coeff.setB1(b1);
        coeff.setB2(b2);
        coeff.setA0(a0);
        coeff.setA1(a1);
        coeff.setA2(a2);
        return coeff;
    }
}
